package com.car.loan.project.tool.util;

/**
 * @author huangding
 * @description
 * @date 2019/10/23 22:29
 */

import static org.apache.commons.codec.binary.Base64.encodeBase64;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.car.loan.framework.web.domain.AjaxResult;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * 使用APPCODE进行云市场ocr服务接口调用
 */
@Slf4j
@Component
public class AliOcrUtil {

    @Value("${ali.ocr.app-code}")
    private String appCOde;

    /**
     * @param type 正反面类型face/back
     */
    public AjaxResult ocrIdCard(String type, byte[] content) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        JSONObject configObj = new JSONObject();
        configObj.put("side", type);
        return postFile(host, path, appCOde, configObj, content);
    }

    /**
     * @param type 正反面类型face/back
     */
    public AjaxResult ocrDivingCard(String type, byte[] content) {
        String host = "https://dm-53.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_vehicle.json";
        JSONObject configObj = new JSONObject();
        configObj.put("side", type);
        return postFile(host, path, appCOde, configObj, content);
    }


    private static AjaxResult postFile(String host, String path, String appCode, JSONObject param,
        byte[] content) {

        Map<String, String> headers = new HashMap<String, String>(1);
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);

        // 对图像进行base64编码
        String imgBase64 = new String(encodeBase64(content));
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            requestObj.put("image", imgBase64);
            if (param.toJSONString().length() > 0) {
                requestObj.put("configure", param.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, "POST", headers, null, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                log.error("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return AjaxResult
                    .error("Http body error msg:" + EntityUtils.toString(response.getEntity()));
            }
            return AjaxResult.success(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            return AjaxResult.error("ocr识别失败请重试");
        }

    }
}